// utils/store.js
// 微信小程序状态管理
import storage from './stotage'
import constant from './constant'
import { getToken, setToken, removeToken } from './auth'

class Store {
  constructor() {
    this.state = {
      token: getToken(),
      id: storage.get(constant.id),
      name: storage.get(constant.name),
      avatar: storage.get(constant.avatar),
      roles: storage.get(constant.roles),
      permissions: storage.get(constant.permissions)
    }
    this.listeners = []
  }
  
  // 订阅状态变化
  subscribe(listener) {
    this.listeners.push(listener)
    return () => {
      const index = this.listeners.indexOf(listener)
      if (index > -1) {
        this.listeners.splice(index, 1)
      }
    }
  }
  
  // 通知状态变化
  notify() {
    this.listeners.forEach(listener => listener(this.state))
  }
  
  // 获取token
  getToken() {
    return this.state.token
  }
  
  // 设置token
  setToken(token) {
    this.state.token = token
    setToken(token)
    this.notify()
  }
  
  // 设置用户ID
  setId(id) {
    this.state.id = id
    storage.set(constant.id, id)
    this.notify()
  }
  
  // 设置用户名
  setName(name) {
    this.state.name = name
    storage.set(constant.name, name)
    this.notify()
  }
  
  // 设置头像
  setAvatar(avatar) {
    this.state.avatar = avatar
    storage.set(constant.avatar, avatar)
    this.notify()
  }
  
  // 设置角色
  setRoles(roles) {
    this.state.roles = roles
    storage.set(constant.roles, roles)
    this.notify()
  }
  
  // 设置权限
  setPermissions(permissions) {
    this.state.permissions = permissions
    storage.set(constant.permissions, permissions)
    this.notify()
  }
  
  // 检查是否已登录
  isLogin() {
    return !!this.state.token
  }
  
  // 清除所有状态
  clear() {
    this.state = {
      token: '',
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: []
    }
    removeToken()
    storage.clean()
    this.notify()
  }
}

// 创建全局store实例
const store = new Store()

export default store